<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账号" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入账号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入昵称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="域名" prop="domainName">
        <el-input v-model="queryParams.domainName" placeholder="请输入域名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="登录页系统名称" label-width="110px" prop="loginName">
        <el-input v-model="queryParams.loginName" placeholder="请输入登录页系统名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="平台标题" prop="platformTitle">
        <el-input v-model="queryParams.platformTitle" placeholder="请输入平台标题" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable style="width: 240px">
          <el-option label="禁用" :value="0" />
          <el-option label="开启" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ecs:platform:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['ecs:platform:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['ecs:platform:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['ecs:platform:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="platformList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" width="100" align="center" prop="userId" />
      <el-table-column label="账号" align="center" prop="userName" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="域名" align="center" prop="domainName" />
      <el-table-column label="logo" align="center" prop="logo">
        <template slot-scope="{ row }">
          <image-preview :src="row.logo" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="登录页系统名称" align="center" prop="loginName" />
      <el-table-column label="平台标题" align="center" prop="platformTitle" />
      <el-table-column label="状态" width="60" align="center" prop="status">
        <template slot-scope="{ row }">
          {{ row.status === 1 ? "开启" : "关闭" }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="合作时间 " align="center" prop="createTime" />
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-position" @click="handleProduct(scope.row)"
            v-hasPermi="['ecs:platform:edit']">产品配置</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ecs:platform:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ecs:platform:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改平台对话框 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="title" :visible.sync="open"
      width="35%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="平台昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入平台昵称" maxlength="30" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="平台账号" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入平台账号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台密码" prop="password" v-if="!form.id" :rules='[
              { required: true, message: "密码不能为空", trigger: "blur" },
              { min: 5, max: 20, message: "密码长度必须介于 5 和 20 之间", trigger: "blur" },
            ]'>
              <el-input v-model="form.password" placeholder="请输入平台密码" type="password" maxlength="20" show-password />
            </el-form-item>
            <el-form-item label="平台密码" prop="password" v-else :rules='[
              { min: 5, max: 20, message: "密码长度必须介于 5 和 20 之间", trigger: "blur" },
            ]'>
              <el-input v-model="form.password" placeholder="请输入平台密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>
        <el-form-item label="平台logo" prop="logo">
          <image-upload :limit="1" v-model="form.logo" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="域名" prop="domainName">
              <el-input v-model="form.domainName" placeholder="请输入域名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名称" prop="loginName">
              <el-input v-model="form.loginName" placeholder="请输入登录页系统名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="平台状态" prop="status">
              <el-select v-model="form.status" placeholder="平台状态" clearable style="width: 240px">
                <el-option label="禁用" :value="0" />
                <el-option label="开启" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台标题" prop="platformTitle">
              <el-input v-model="form.platformTitle" placeholder="请输入平台标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="产品市场" :visible.sync="openProduct"
      width="45%" append-to-body>
      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编码" align="center" prop="id" />
        <el-table-column label="logo" align="center" prop="logo">
          <template slot-scope="{ row }">
            <image-preview :src="row.logo" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="平台费率/%" width="210" align="center" prop="feeRate">
          <template slot-scope="{ row }">
            <el-form v-if="row.id === editProductId" :model="row" ref="tableForm">
              <el-form-item prop="splitFeeRate" v-if="row.id !== 1" :rules='[
                { required: true, message: "平台费率不能为空", trigger: "blur" },
                { type: "number", message: "平台费率为数字", trigger: "blur" },
              ]'>
                <el-input-number :step="0.1" :min="0.1" :max="10" size="mini" :precision="2" v-model="row.splitFeeRate"
                  placeholder="请输入平台费率" />
              </el-form-item>
              <el-form-item prop="splitFeeRate" v-else-if="row.id === 1" :rules='[
                { required: true, message: "平台费率不能为空", trigger: "blur" },
              ]'>
                <el-select v-model="row.splitFeeRate" placeholder="请选择平台费率">
                  <el-option label="0.2%" :value="0.2"></el-option>
                  <el-option label="0.25%" :value="0.25"></el-option>
                  <el-option label="0.3%" :value="0.3"></el-option>
                  <el-option label="0.4%" :value="0.4"></el-option>
                  <el-option label="0.5%" :value="0.5"></el-option>
                  <el-option label="0.6%" :value="0.6"></el-option>
                  <el-option label="0.8%" :value="0.8"></el-option>
                </el-select>
              </el-form-item>

            </el-form>
            <template v-else>{{ row.splitFeeRate ? row.splitFeeRate : row.feeRate }}%</template>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{ row }">
            <div v-if="row.id !== editProductId">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleProductUpdate(row)"
                v-hasPermi="['ecs:platform_product:edit']">修改</el-button>
            </div>
            <div v-else>
              <el-button size="mini" type="text" @click="handProductSave(row)">保存</el-button>
              <el-button size="mini" type="text" @click="handProductCancel(row)">取消</el-button>
            </div>

          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { updateUserProduct } from "@/api/ecs/userProduct";
import { listPlatform, getPlatform, delPlatform, addPlatform, updatePlatform } from "@/api/ecs/platform";
import { listProduct } from '@/api/ecs/product'

export default {
  name: "Platform",
  data() {
    var checkDomainName = (rule, value, callback) => {
      const isValid = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(value);
      if (!isValid) {
        callback(new Error('请输入有效域名'));
      } else {
        callback();
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedUser: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台表格数据
      platformList: [],
      // 产品表格数据
      productList: [],
      productData: {},
      editProductId: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openProduct: false,
      initPassword: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        nickName: '',
        domainName: '',
        loginName: '',
        platformTitle: '',
        status: '',
        userId: null,
        logo: null,
        domainName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户编码不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "平台账号不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '平台账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "平台昵称不能为空", trigger: "blur" }
        ],
        logo: [
          { required: true, message: "请上传平台logo", trigger: "blur" }
        ],
        password: [
          // { required: true, message: "密码不能为空", trigger: "blur" },
          // { min: 5, max: 20, message: '密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        domainName: [
          { required: true, message: "域名不能为空", trigger: "blur" },
          { validator: checkDomainName, trigger: 'blur' }
        ],
        loginName: [
          { required: true, message: "登录页系统名称不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "平台联系电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的联系电话",
            trigger: "blur"
          }
        ],
        platformTitle: [
          { required: true, message: "平台标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询平台列表 */
    getList() {
      this.loading = true;
      listPlatform(this.queryParams).then(response => {
        this.platformList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        logo: null,
        domainName: null,
        loginName: null,
        platformTitle: null,
        createTime: null,
        updateTime: null,
        delFlag: null,
        status: null,
        createBy: null,
        updateBy: null,
        password: null,
        userName: null,
        nickName: null,
        remark: null,
        phoneNumber: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.status = 1
      this.form.password = this.initPassword;
      this.title = "添加平台";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlatform(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改平台";
      });
    },


    handleProduct(row) {
      this.openProduct = true;
      this.form.id = row.id
      this.editProductId = 0
      listProduct({ splitId: row.id, type: 1 }).then(response => {
        this.productList = response.rows;
      });
    },

    handleProductUpdate(row) {
      this.productData = { ...row }
      if (!row.splitFeeRate) {
        row.splitFeeRate = row.feeRate
      }
      this.editProductId = row.id
    },
    handProductSave(row) {
      this.$refs["tableForm"].validate(valid => {
        if (valid) {
          updateUserProduct({ productId: row.id, splitId: this.form.id, splitFeeRate: row.splitFeeRate, type: 1 }).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.editProductId = 0
            this.handleProduct();
          });
        }
      })
    },
    handProductCancel(row) {
      Object.assign(row, this.productData)
      this.editProductId = 0
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlatform(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlatform(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除平台编号为"' + ids + '"的数据项？').then(function () {
        return delPlatform(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ecs/platform/export', {
        ...this.queryParams
      }, `platform_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
